package com.example.mymvvmdemo.models.my_article;


import android.app.Activity;
import android.content.Intent;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivityMyArticleBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.models.main.fragment.home.entity.BlogArticlesEntity;
import com.example.mymvvmdemo.models.my_article.adapter.MyArticleAdapter;
import com.example.mymvvmdemo.net.presenter.DeletePresenter;
import com.example.mymvvmdemo.net.presenter.GetPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;

public class MyArticleActivity extends BaseLoadActivity<ActivityMyArticleBinding> implements View.OnClickListener, IView.GetView, IView.DeleteView, MyArticleAdapter.ArticleListener {

    public static void startMyArticleActivity(Activity activity) {
        Intent intent = new Intent(activity, MyArticleActivity.class);
        activity.startActivity(intent);
    }

    private MyArticleViewModel viewModel;
    private GetPresenter getPresenter;
    private DeletePresenter deletePresenter;
    private MyArticleAdapter homeAdapter;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;


    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {

        viewModel = new ViewModelProvider(this).get(MyArticleViewModel.class);
        getPresenter = new GetPresenter(this);
        deletePresenter = new DeletePresenter(this);

        initTitle(getString(R.string.my_article));
        initAdapter();
        startLoadData();

    }

    @Override
    protected void initListener() {

        binding.include.ivBack.setOnClickListener(this);
        binding.include.ivRight.setOnClickListener(this);
        binding.include.ivRight2.setOnClickListener(this);
        binding.tvCancel.setOnClickListener(this);
        binding.tvDelete.setOnClickListener(this);

        binding.refreshViewShowContent.setOnRefreshListener(relayout -> {
            viewModel.isRefresh = true;
            startLoadData();
        });
        binding.refreshViewShowContent.setOnLoadMoreListener(relayout -> {
            //当前不需要分页加载，后续再加
//            mainViewModel.isRefresh = false;
            startLoadData();
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_right:
                viewModel.startAddArticleActivity(this);
                break;
            case R.id.iv_right2:
                viewModel.isEdit = !viewModel.isEdit;
                homeAdapter.changeEditModel(viewModel.isEdit);
                binding.clEdit.setVisibility(viewModel.isEdit ? View.VISIBLE : View.GONE);
                break;
            case R.id.tv_cancel:
                disMissEditModel();
                break;
            case R.id.tv_delete:
                deleteArticle();
                break;
            default:
                break;
        }
    }

    /***********************************自定义方法**************************************/
    private void deleteArticle() {
        int selectPosition = getSelectPosition();
        if (selectPosition == -1) {
            toast(R.string.delete_article_select, ToastUtils.TOA_W);
            return;
        }
        BlogArticlesEntity.DataDTO dataDTO = homeAdapter.getDataList().get(selectPosition);
        viewModel.id = dataDTO.getId();
        LogUtils.d("viewModel.id:" + viewModel.id);
        startLoadDelete();
        disMissEditModel();
    }

    public int getSelectPosition() {
        List<BlogArticlesEntity.DataDTO> dataList = homeAdapter.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            boolean select = dataList.get(i).isSelect();
            if (select) {
                return i;
            }
        }
        return -1;
    }

    public void disMissEditModel() {
        viewModel.isEdit = false;
        homeAdapter.changeEditModel(false);
        binding.clEdit.setVisibility(View.GONE);
    }

    public void initTitle(String title) {
        binding.include.tvTitle.setVisibility(View.VISIBLE);
        binding.include.tvTitle.setText(title);
        binding.include.ivRight.setVisibility(View.VISIBLE);
        binding.include.ivRight.setImageResource(R.drawable.ic_svg_add_black);
        binding.include.ivRight2.setVisibility(View.VISIBLE);
        binding.include.ivRight2.setImageResource(R.drawable.ic_svg_edit_black);

    }

    private void initAdapter() {
        homeAdapter = new MyArticleAdapter(this, viewModel.articleList);
        homeAdapter.setListener(this);
        binding.recyclerView.setAdapter(homeAdapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    public void startLoadData() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.blogArticles, hashMap, UrlTypeConstants.blogArticles);
    }

    public void startLoadDelete() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", "" + viewModel.id);
        deletePresenter.startLoadDelete(UrlConstants.deleteArticles, hashMap, UrlTypeConstants.deleteArticles);
    }

    private void deviceComplete() {
        try {
            binding.refreshViewShowContent.finishRefresh();
            binding.refreshViewShowContent.finishLoadMore();
            homeAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            LogUtils.e("deviceComplete error:" + e.getMessage());
        }
    }

    /*************************************数据请求回调*********************************************/
    @Override
    public void loadGetSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.blogArticles)) {
            loadBlogArticlesSuccess(result, code);
        }
    }

    @Override
    public void loadGetFail(String message, String type) {
        if (type.equals(UrlTypeConstants.blogArticles)) {
            loadBlogArticlesFail();
        }
    }

    @Override
    public void loadGetAccountError(int code) {

    }

    @Override
    public void loadGetNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadDeleteSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.deleteArticles)) {
            loadDeleteArticlesSuccess(result, code);
        }
    }

    @Override
    public void loadDeleteFail(String message, String type) {
        if (type.equals(UrlTypeConstants.deleteArticles)) {
            loadDeleteArticlesFail();
        }
    }

    @Override
    public void loadDeleteAccountError(int code) {

    }

    @Override
    public void loadDeleteNetWorkError(String message) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }


    /**************************************处理请求后数据***********************************************/
    private void loadDeleteArticlesSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message1 = registerFailEntity.getMessage();
            if (!StrUtils.isEmpty(message1)) {
                toast(message1, ToastUtils.TOA_W);
                return;
            }
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        startLoadData();

    }

    private void loadDeleteArticlesFail() {
        toast(R.string.delete_article_fail, ToastUtils.TOA_W);
        dismissDialog();
    }

    private void loadBlogArticlesSuccess(String result, int code) {

        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        try {
            BlogArticlesEntity blogArticlesEntity = gson.fromJson(result, BlogArticlesEntity.class);
            List<BlogArticlesEntity.DataDTO> data = blogArticlesEntity.getData();

            if (data == null) {
                loadBlogArticlesFail();
                return;
            }
            if (data.size() == 0) {
                loadBlogArticlesFail();
                return;
            }
            if (viewModel.isRefresh) {
                viewModel.articleList.clear();
            }
            viewModel.articleList.addAll(data);
            homeAdapter.notifyDataSetChanged();

            deviceComplete();

        } catch (Exception e) {
            loadBlogArticlesFail();
        }
    }

    private void loadBlogArticlesFail() {
        deviceComplete();
        dismissDialog();
    }


    /*******************************************适配器回调*******************************************/
    @Override
    public void onMyArticleClick(int position) {
        List<BlogArticlesEntity.DataDTO> dataList = homeAdapter.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            dataList.get(i).setSelect(i == position);
        }
        homeAdapter.notifyDataSetChanged();
    }

}